import time
import traceback
from datetime import datetime
from applications.models import Session
from applications.models.novel import NovelList, NovelMenu
from applications.services.novel import addBookShelfTask, start_source_update_task_func

def start_task(scheduler):

    @scheduler.scheduled_job('interval', hours=3) # 'date', run_date=datetime.now()
    # 每三小时更新一次书籍
    def start_novel_update_task():
        print("更新书籍 开始")
        session = Session()
        try:

            books = session.query(NovelList).filter(NovelList.enable == 1, NovelList.update_status == 0).all()
            for b in books:
                last_chapter = session.query(NovelMenu).filter(NovelMenu.novel_id == b.id).order_by(NovelMenu.order.desc()).first()
                start_chapter = last_chapter.order
                end_chapter = start_chapter + 1000

                # 更新章节, 添加一个立即执行的任务
                print("更新书籍 开始", b.name, start_chapter, end_chapter)
                scheduler.add_job(addBookShelfTask, 'date', run_date=datetime.now(), args=[None, b.id, b.address, start_chapter, end_chapter, False])

        except Exception:
            print("更新书籍 异常", traceback.format_exc())
            session.rollback()

        finally:
            session.close()
            print("更新书籍 完成")

    @scheduler.scheduled_job('interval', hours=2)
    # 每五小时更新一次书籍书源
    def start_source_update_task():
        start_source_update_task_func()